import React from "react";
import { Button, Form, Input, message } from "antd";
import store from "store2";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import loginStyle from "@/styles/login.module.less";
import { adminLoginInterface } from "@/api/admin";
import { useDispatch } from "react-redux";
import { setLoginState, setAdminUserInfo } from "@/store/modules/admin";
export default function Login() {
  const [messageApi, contextHolder] = message.useMessage();
  const dispatch = useDispatch();
  
  const onFinish = (values) => {
    adminLoginInterface(values).then((res) => {
      switch (res.data.code) {
        case "10005":
          messageApi.error(res.data.message);
          break;
        case "10003":
          messageApi.error(res.data.message);
          break;
        default:
          const userData = {
            adminname: res.data.data.adminname,
            role: res.data.data.role,
            checkedKeys: res.data.data.checkedkeys,
            token: res.data.data.token,
          };
          store.set("users", { ...userData, loginState: true });
          dispatch(setLoginState(true));
          dispatch(setAdminUserInfo(userData));
          break;
      }
    });
  };

  return (
    <div className={loginStyle.login}>
      <div className={loginStyle["login-box"]}>
        <h3>后台管理系统</h3>
        <Form name="basic" initialValues={{adminname:'admin',password:'123456'}} onFinish={onFinish} autoComplete="off">
          <Form.Item
            name="adminname"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder="用户名" prefix={<UserOutlined />} />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password placeholder="密码" prefix={<LockOutlined />} />
          </Form.Item>
          <Form.Item>
            <Button
              className={loginStyle["login-form-button"]}
              type="primary"
              htmlType="submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
        {contextHolder}
      </div>
    </div>
  );
}
